import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';


/// 批量删除资料库
class HandleSmartHomeImagePage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "HandleSmartHomeImagePage";
  final String stid;
  final String style;
  final String shid;
  const HandleSmartHomeImagePage({Key key,this.stid, this.style, this.shid})
      : super(key: key);

  @override
  HandleSmartHomeImagePageState createState() => HandleSmartHomeImagePageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String stid, String style, String shid) {
    return RouterUtils.routeForFutureResult(
      context,
      HandleSmartHomeImagePage(
          stid:stid,
          style:style,
          shid:shid
      ),
      routeName: HandleSmartHomeImagePage.ROUTER,
    );
  }
}

class HandleSmartHomeImagePageState
    extends BasePagerState<SmartHomeStoreDetailListItemBean, HandleSmartHomeImagePage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin {
  SmartHomeStoreDetailViewModel _viewModel;

  ///获取state
  static HandleSmartHomeImagePageState of(BuildContext context) {
    final HandleSmartHomeImagePageState result =
    context.findAncestorStateOfType<HandleSmartHomeImagePageState>();
    return result;
  }

  List<String> _toDeleteList;
  List<String> _toDeleteVideoList;

  bool isAliveConfirm = false;

  @override
  void initState() {
    super.initState();
    _toDeleteList = new List();
    _toDeleteVideoList = new List();
    _viewModel = new SmartHomeStoreDetailViewModel(this, stid: widget?.stid,
        style: widget?.style, shid: widget?.shid);
    _viewModel?.refresh();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return LightAnnotatedRegion(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: _toMainColumnWidget(),
      ),
    );
  }
  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }
  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(
          child: _toMainPlaceHolderWidget(),
        )
      ],
    );
  }

  Widget _toTopBarWidget() {
    final double statusHeight = ScreenUtils.getStatusBarH(context);
    return Container(
      height: 44 + statusHeight,
      color: Color(0xFFF6F7F9),
      padding: EdgeInsets.only(top: statusHeight),
      child: Row(
        children: <Widget>[
          SizedBox(
            width: 15,
          ),
          Text(
            _toDeleteList.length>0?"已选择${_toDeleteList.length}":"请选择",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                fontSize: 17,
                height: 1.22,
                fontWeight: FontWeight.w600),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              RouterUtils.pop(context);
            },
            child: Container(
              padding: const EdgeInsets.only(left: 10,right: 10),
              height: 23,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.all(Radius.circular(12)),
                border:  Border.all(
                    color: Color(0xFFB0B3BF),
                    width: 1),
              ),
              child: Text(
                "取消",
                style: TextStyle(
                    fontSize: 12,
                    height: 1.2,
                    color: Color(0xFF5E687C)
                ),
              ),
            ),
          ),
          SizedBox(
            width: 15,
          ),
        ],
      ),
    );
  }

  Widget _toMainPlaceHolderWidget() {
    return Column(
      children: <Widget>[
        Expanded(
          child: ScrollConfiguration(
              behavior: MyBehavior(),
              child: _toPlaceHolderWidget(
                  child: _toGridWidget())
          ),
        ),
        _toBottomWidget(),
      ],
    );
  }

  Widget _toBottomWidget(){
    final double bottomH = ScreenUtils.getBottomBarH(context);
    return Container(
      margin: EdgeInsets.only(bottom: bottomH),
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: isAliveConfirm,
        height: 49,
        radius: BorderRadius.all(Radius.circular(0)),
        width: ScreenUtils.screenW(context),
        margin: const EdgeInsets.symmetric(horizontal: 0),
        unSelectBgColor: Color(0xFFF6F7F9),
        selectedBgColor:
        ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
          color: Color(0xFFB0B3BF),
          fontSize: 17,
        ),
        selectedTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 17,
        ),
        text: "删除文件",
        onTap: ()async{
          if(_toDeleteList != null && _toDeleteList.length > 0){
            String ids = "";
            _toDeleteList.forEach((element) {
              ids += element;
              ids += ",";
            });
            String videoIds = "";
            _toDeleteVideoList.forEach((element) {
              videoIds += element;
              videoIds += ",";
            });
            bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
              title: "提示",
              content: "选中文件删除后无法找回，确认继续？",
              cancelText: "取消",
              confirmText: "确认",
              confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              cancelBgColor: Color(0xFFF6F7F9),
              titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              widgetBgColor: Colors.white,
            );
            if (result ?? false) {
              if(StringUtils.isNotEmpty(ids)){
                ids = ids.substring(0, ids.length-1);
              }
              _viewModel.deleteImage(context, ids, videoIds, widget?.shid);
            }

          }
        },
      ),
    );
  }

  Widget _toPlaceHolderWidget({Widget child}) {
    return VgPlaceHolderStatusWidget(
        emptyStatus: data == null || data.isEmpty,
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
        errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
        loadingStatus: data == null,
        child: VgPullRefreshWidget.bind(
            state: this,
            refreshBgColor: Colors.white,
            viewModel: _viewModel, child: child));
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toGridWidget(){
    return ScrollConfiguration(
        behavior: MyBehavior(),
        child: GridView.builder(
          padding: EdgeInsets.only(
              left: 15,
              right: 15,
              top: 10,
              bottom: getNavHeightDistance(context)),
          itemCount: data?.length ?? 0,
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 4,
            crossAxisSpacing: 5,
            childAspectRatio: 1 / 1,
          ),
          itemBuilder: (BuildContext context, int index) {
            return _toGridItemWidget(context,data?.elementAt(index));
          },
        ));
  }

  Widget _toGridItemWidget(BuildContext context, SmartHomeStoreDetailListItemBean itemBean) {
    double width = ScreenUtils.screenW(context) - 30 -10;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        _onTap(itemBean);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            VgCacheNetWorkImage(
              itemBean?.getCoverUrl() ?? "",
              width:width,
              height: width,
              imageQualityType: ImageQualityType.middleDown,
            ),
            Offstage(
              offstage: !(itemBean?.isVideo() ?? false),
              child: Opacity(
                opacity: 0.5,
                child: Image.asset(
                  "images/video_play_ico.png",
                  width: 40,
                ),
              ),
            ),
            Positioned(
              top: 0,
              right: 0,
              child: Offstage(
                offstage: !(itemBean?.isVideo() ?? false),
                child: Container(
                  width: 33,
                  height: 14,
                  decoration: BoxDecoration(
                      color: VgColors.INPUT_BG_COLOR,
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(4),
                          topRight: Radius.circular(4))),
                  child: Center(
                    child: Text(
                      VgDateTimeUtils.getSecondsToMinuteStr(itemBean?.videotime) ?? "00:00",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 9,
                          height: 1.2
                      ),
                    ),
                  ),
                ),
              ),
            ),
            AnimatedOpacity(
              duration: DEFAULT_ANIM_DURATION,
              opacity:
              itemBean.selectStatus??false
                  ? 0.3
                  : 0,
              child: Container(
                color: Colors.white,
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: _toSelectWidget(itemBean?.selectStatus??false),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toSelectWidget(bool selectStatus){
    return AnimatedSwitcher(
      duration: DEFAULT_ANIM_DURATION,
      child:  Image.asset(
        selectStatus?"images/icon_select_delete.png":"images/icon_unselect_delete.png",
        width: 20,
      ),
    );
  }

  void _onTap(SmartHomeStoreDetailListItemBean itemBean) {
    if (itemBean == null) {
      return null;
    }
    _handleSelectedStatus(itemBean);
  }

  ///处理选中状态
  void _handleSelectedStatus(SmartHomeStoreDetailListItemBean itemBean) {
    if (itemBean == null || StringUtils.isEmpty(itemBean.picid)) {
      VgToastUtils.toast(context, "错误资源");
      return;
    }
    if (itemBean?.selectStatus??false) {
      _removeLabel(itemBean.picid, itemBean?.videoid);
    } else {
      _addLabel(itemBean.picid, itemBean?.videoid);
    }
  }

  void _addLabel(String selectedId, String videoId) {
    _toDeleteList?.add(selectedId);
    if(StringUtils.isNotEmpty(videoId)){
      _toDeleteVideoList?.add(videoId);
    }
    _handleUpdateList(data);
  }

  void _removeLabel(String removeId, String videoId) {
    _toDeleteList?.remove(removeId);
    if(StringUtils.isNotEmpty(videoId)){
      _toDeleteVideoList?.remove(videoId);
    }
    _handleUpdateList(data);
  }

  void _handleUpdateList(List<SmartHomeStoreDetailListItemBean> list) {
    if (list == null || list.isEmpty) {
      return;
    }
    list?.removeWhere((element) => StringUtils.isEmpty(element?.picid));
    for (SmartHomeStoreDetailListItemBean item in list) {
      if(_toDeleteList.contains(item.picid)){
        item.selectStatus = true;
      }else{
        item.selectStatus = false;
      }
    }

    isAliveConfirm = _toDeleteList.length>0;

    print("打印结果"
        "\n"
        "${_toDeleteList.toString()}");
    setState(() {});
  }



  @override
  bool get wantKeepAlive => true;
}
